// server.js
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const cors = require('cors');
const fs = require('fs');
var WebSocket = require('ws');
const app = express();
const PORT = 3001;

const wss = new WebSocket.Server({ port: 8082 });
wss.on('connection', (ws) => {
    console.log('Client connected');

    ws.on('message', (message) => {
        console.log(message, '>>>')
        // 将接收到的消息广播给所有连接的客户端
        wss.clients.forEach((client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });
    ws.on('close', function close() {
        console.log('Client disconnected');
    });
});


const allowedOrigins = [
    'https://example.com',
    'https://another-example.com',
    'http://localhost:3000' // 允许本地开发时的访问
];

// 使用 cors 中间件，允许所有来源
app.use(cors({
    origin: function (origin, callback) {
        // 允许没有 origin 的请求，比如来自 Postman
        if (!origin || allowedOrigins.indexOf(origin) !== -1) {
            callback(null, origin);
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    },
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // 允许的方法
    credentials: true, // 允许携带凭证
    optionsSuccessStatus: 204 // 对于 IE 11 和一些旧版本的浏览器，使用204状态
}));


// 使用 morgan 进行请求日志记录
app.use(morgan('dev'));

// 提供 HLS 视频流
app.use('/video', express.static(path.join(__dirname, 'allVideo')));


// 新增路由以获取视频文件夹数量
app.get('/api/video-folder-count', (req, res) => {
    const videoDir = path.join(__dirname, 'allVideo');

    fs.readdir(videoDir, { withFileTypes: true }, (err, files) => {
        if (err) {
            console.error('Error reading directory:', err);
            return res.status(500).json({ error: 'Failed to read directory' });
        }

        // 过滤出文件夹
        const folderCount = files.filter(file => file.isDirectory()).length;

        res.json({ count: folderCount });
    });
});
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
